package cn.itsource.ymcc.userdetails;

import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.domain.Permission;
import cn.itsource.ymcc.mapper.PermissionMapper;
import cn.itsource.ymcc.service.ILoginService;
import cn.itsource.ymcc.service.IPermissionService;
import cn.itsource.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Repository
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private ILoginService loginService;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //根据用户名查询
        EntityWrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username",s);
        Login login = loginService.selectOne(wrapper);
        AssertUtil.isNotNull(login,"该用户不存在");
        //查询权限
        List<Permission> list = permissionMapper.selectByLoginId(login.getId());

        List<SimpleGrantedAuthority> authorityList = list.stream().map(permission -> {
            return new SimpleGrantedAuthority(permission.getSn());
        }).collect(Collectors.toList());

        //封装login
        UserDetails user = new User(
                JSON.toJSONString(login),
                login.getPassword(),
                login.getEnabled(),
                login.getAccountNonExpired(),
                login.getCredentialsNonExpired(),
                login.getAccountNonLocked(),
                authorityList
        );


        return user;
    }
}
